#include "netdisk.h"
//#define THRESHOLD 1024
//#define INIT_LENGTH 128
//
//typedef struct string_t{
//    char* str;
//    int length;
//}String;

//int init_stack(Stack_t* stack){
//    stack = (Stack_t*)calloc(1, sizeof(Stack_t));
//    ERROR_CHECK(stack, NULL, "calloc");
//    return 0;
//}

bool is_empty(Stack_t dir){
    return dir.stackSize == 0;
}

int pop(Stack_t* dir, char* del_data){
    if(is_empty(*dir)){
        return -1;
    }
    memcpy(del_data, dir->pTop->data, strlen(dir->pTop->data) + 1); // 把栈顶元素拷贝到del_data中

    Note_t* pFree = dir->pTop;      // 栈顶结点设为要释放的结点
    dir->pTop = pFree->pnext;       // 栈顶指向下一个指针
    
    --(dir->stackSize);             // 栈大小减一

    if(dir->stackSize == 0){        // 若栈空则把栈底指针指向空
        dir->pBottom = NULL;
    }

    free(pFree->data);
    free(pFree);
    
    return 0;
}

int push(Stack_t* dir, char* add_data){
    Note_t* newNode = (Note_t*)malloc(sizeof(Note_t));
    ERROR_CHECK(newNode, NULL, "malloc");

    // 初始化结点值
    newNode->data = (char*)malloc(strlen(add_data)+1);
    memcpy(newNode->data, add_data, strlen(add_data));
    newNode->data[strlen(add_data)] = '\0';
    newNode->pnext = dir->pTop;

    ++(dir->stackSize);     // 更新栈的大小
    dir->pTop = newNode;

    // 若更新完栈的大小为1时，同时更新栈底指针
    if(dir->stackSize == 1){
        dir->pBottom = newNode;
    }

    return 0;
}

int travel_stack(Stack_t dir, char* working_dir){
    char buf1[4096] = {0};
    char target_buf[8000] = {0};
    Note_t* curr = dir.pTop;
    while(curr != NULL){
        sprintf(target_buf, "%s/%s", curr->data, buf1);
        memcpy(buf1, target_buf, strlen(target_buf));
        curr = curr->pnext;
    }

    memcpy(working_dir, target_buf, strlen(target_buf) - 1);
    working_dir[strlen(target_buf) - 1] = '\0';
    return 0;
}

int destroy_stack(Stack_t* dir){
    char del[4096] = {0};
    for(int i = 0; i < dir->stackSize; ++i){
        pop(dir, del);
    }
    bzero(dir, sizeof(*dir));
}

void print_stack(Stack_t dir){
    for(int i = 0; i < dir.stackSize; ++i){
        printf("%s\n", dir.pTop->data);
        dir.pTop = dir.pTop->pnext;
    }
}
